import { _decorator, Node, instantiate, UITransform, Input, EventTouch, Label, TERRAIN_HEIGHT_BASE } from 'cc';
import CCUtils from '../util/CCUtils';
import { CardItem } from './CardItem';
import { allColumn, comboLimitMaxNum, gameConst, LayerInfo, selectMaxNum } from './GameConst';
import { LayerItem } from './LayerItem';

class GameManager {
    
    /**存放layer的容器 */
    private allContainer:Node = null;
    /**存放已经选中的卡牌的容器 */
    private selectContainer:Node = null;
    private delectCount:Label = null;
    private delectLayers:Label = null;
    private comboLabel:Label = null
    private superBtn:Node = null;

    private allContainer_UITransform:UITransform = null;
    private selectContainer_UITransform:UITransform = null;

    private selectCardsArr:CardItem[] = [];


    private _delectCountNum:number = 0;
    private _delectLayersNum:number = 0;

    private _clickIndex:number = 0;
    private _lastComboClickIndex:number = 0;
    private _comboNum:number = 0;

    /**
     * init
     */
    public init( gameNode:Node) {

        this._delectCountNum = 0;
        this._delectLayersNum = 0;

        this.allContainer = CCUtils.findChild(gameNode,"allContainer");
        this.selectContainer = CCUtils.findChild(gameNode,"selectContainer");

        this.delectCount = CCUtils.getLabel(gameNode,"delectCount");
        this.delectLayers = CCUtils.getLabel(gameNode,"delectLayers");
        this.comboLabel = CCUtils.getLabel(gameNode,"comboLabel");

        this.superBtn = CCUtils.findChild(gameNode,"superBtn");
        this.superBtn.on(Input.EventType.TOUCH_END, this.onClickSuperBtn, this)

        this.allContainer_UITransform = this.allContainer.getComponent(UITransform);
        this.selectContainer_UITransform = this.selectContainer.getComponent(UITransform);

        this.addLayer().addSomeCard(10);
        this.addLayer().addSomeCard(10);
        this.addLayer().addSomeCard(10);
        
    }


    /**添加一个层 */
    private addLayer():LayerItem {
        let layer:Node = instantiate(gameConst.globelPrefab.layerPrefab);
        let item:LayerItem = layer.getComponent(LayerItem); 
        // this.allContainer.addChild(layer);
        this.allContainer.insertChild(layer,0);
        item.init();
        return item;
    }


    /**
     * 删除层
     * @param layer 
     */
    public removeLayer(layer:number|Node) {
        // object
        if ( typeof layer == "number") {
            for (let index = 0; index < this.allContainer.children.length; index++) {
                let node:Node = this.allContainer.children[index];
                let layerItem:LayerItem = node.getComponent(LayerItem);
                if (layerItem.info.layerId == layer) {
                    node.removeFromParent();
                    return;
                }
            }
        }else{
            layer.removeFromParent();
        }
    }

    /**
     * 根据新添加的item，检测结果
     * @param ClickItem 
     * @returns 
     */
    private checkResult(ClickItem:CardItem) {

        if (this.selectCardsArr.length < 3) {
            return;
        }
        
        this._clickIndex ++;

        let clickIndex:number = this.selectCardsArr.indexOf(ClickItem);
        let beginIndex:number = clickIndex-2<0?0:clickIndex-2;
        let endIndex:number = clickIndex+3;
        let checkCardList:CardItem[] = this.selectCardsArr.slice(beginIndex,endIndex);
        console.log("检测的数组", clickIndex, checkCardList);

        let sameCount:number = 0;
        for (let index = 0; index < checkCardList.length; index++) {
            let item:CardItem = checkCardList[index];
            if (item.type == ClickItem.type) {
                sameCount ++;
            }else{
                sameCount = 0;
            }
        }

        if (sameCount >= 3) { //有相同的了，全部消掉！
            this._delectCountNum ++;
            this.delectCount.string = this._delectCountNum.toString();

            if (this._clickIndex - this._lastComboClickIndex <= comboLimitMaxNum && this._lastComboClickIndex > 0) {
                this._comboNum ++;
            }

            for (let index = this.selectCardsArr.length-1; index >=0 ; index--) {
                let item:CardItem = this.selectCardsArr[index];
                if (item.type == ClickItem.type) {
                    this.selectCardsArr.splice(index,1);
                    item.node.removeFromParent();
                }
            }


            for (let index = 0; index < this.allContainer.children.length; index++) {
                let layer:Node = this.allContainer.children[index];
                let layerItem:LayerItem = layer.getComponent(LayerItem);
                if (layerItem.info.layerId == ClickItem.belongLayer.layerId) {
                    if (layerItem.checkLayerClear(this.selectCardsArr)) { 
                        console.log("成功消除了这个层", layerItem.info.layerId);
                        this.removeLayer(layerItem.node);
                        this._delectLayersNum ++;
                        this.delectLayers.string = this._delectLayersNum.toString();
                        this.autoAddLayer();
                    }
                }
            }

            this._lastComboClickIndex = this._clickIndex;
            if (this._comboNum == 0) {
                this._comboNum = 1;
            }

        }else{

            if (this._clickIndex - this._lastComboClickIndex >= comboLimitMaxNum) {
                this._comboNum == 0;
            }
        }

        if (this._comboNum > 1) {
            this.comboLabel.string = this._comboNum.toString();
        }else{
            this.comboLabel.string = "0";
        }
    }

    private onClickSuperBtn(e:EventTouch) {

        for (let index = this.selectCardsArr.length-1; index >=0 ; index--) {
            let item:CardItem = this.selectCardsArr[index];
            this.selectCardsArr.splice(index,1);
            item.node.removeFromParent();

            for (let index = 0; index < this.allContainer.children.length; index++) {
                let layer:Node = this.allContainer.children[index];
                let layerItem:LayerItem = layer.getComponent(LayerItem);
                if (layerItem.info.layerId == item.belongLayer.layerId) {
                    if (layerItem.checkLayerClear(this.selectCardsArr)) {
                        console.log("成功消除了这个层", layerItem.info.layerId);
                        this.removeLayer(layerItem.node);
                        this._delectLayersNum ++;
                        this.delectLayers.string = this._delectLayersNum.toString();
                        this.autoAddLayer();
                    }
                }
            }
        }
        
    }


    /**
     * 选中区域的卡牌是不是满了，true满了
     * @returns 
     */
    public isSelectContainerFull():boolean{
        if (this.selectContainer && this.selectContainer.children.length >= selectMaxNum) {
            return true;
        }
        return false;
    }


    /**
     * 选中卡牌
     * @param clickItem 
     */
    public selectCard(clickItem:CardItem):void{

        this.updateAllLayerCoverByRemoveCard(clickItem);


        this.selectCardsArr.push(clickItem);
        this.selectCardsArr.sort((a:CardItem,b:CardItem)=>{
            if (a.type > b.type) {
                return 1;
            }else{
                return -1;
            }
        });
        this.selectContainer.addChild(clickItem.node);

        for (let index = 0; index < this.selectCardsArr.length; index++) {
            let card:CardItem = this.selectCardsArr[index];
            card.node.setSiblingIndex(index);
        }

        setTimeout(() => {
            this.checkResult(clickItem);
        }, 200);

    }



    /**
     * 根据选中的卡牌（移除了这个卡牌,顶部）,刷新所有在这个卡牌之下的层级的覆盖关系
     * @param clickItem 
     */
    private updateAllLayerCoverByRemoveCard(clickItem:CardItem){

        let beginX:number = Math.max(clickItem.pos.gridX - 1, 0); 
        let beginY:number = Math.max(clickItem.pos.gridY - 1, 0); 
        let endX:number = Math.min(clickItem.pos.gridX + 1, allColumn-1); 
        let endY:number = Math.min(clickItem.pos.gridY + 1, allColumn-1); 


        // console.log("移除的卡牌",clickItem.belongLayer.layerId, clickItem.pos.gridX, clickItem.pos.gridY);

    
        for (let index = 0; index < this.allContainer.children.length; index++) {
            let layer:Node = this.allContainer.children[index];
            let layerItem:LayerItem = layer.getComponent(LayerItem);
            // console.log("遍历层",index, layerItem.info.layerId);
            if (layerItem.info.layerId == clickItem.belongLayer.layerId) {
                return;
            }

            // console.log("需要检查的层id", layerItem.info.layerId);

            let checkLayer:LayerInfo = layerItem.info;
            for (let x:number = beginX; x <= endX; x++) {
                for (let y:number = beginY; y <= endY; y++) {
                    let checkCard:CardItem = checkLayer.allCards.get(`${x}_${y}`);
                    if (checkCard == null) {
                        continue;
                    }
                    let result:boolean = false;//默认没被覆盖。
                    for (let index2 = index+1; index2 < this.allContainer.children.length; index2++) {
                        let coverlayer:Node = this.allContainer.children[index2];
                        let coverlayerItem:LayerItem = coverlayer.getComponent(LayerItem);
                        if (coverlayerItem.checkCardBeCover(checkCard)) {
                            result = true;
                            break;
                        }
                    }
                    // console.log("检测的卡牌",checkCard.belongLayer.layerId, checkCard.pos.gridX, checkCard.pos.gridY,result);
                    checkCard.beCover = result;
                }
            }
        }
    }



    /**
     * 根据选中的卡牌（添加这个卡牌,底部）,刷新这个卡牌的覆盖关系
     * @param addItem 
     */
    public updateCardCoverByAddCard(addItem:CardItem){

        let beginX:number = Math.max(addItem.pos.gridX - 1, 0); 
        let beginY:number = Math.max(addItem.pos.gridY - 1, 0); 
        let endX:number = Math.min(addItem.pos.gridX + 1, allColumn-1); 
        let endY:number = Math.min(addItem.pos.gridY + 1, allColumn-1); 

        for (let index = this.allContainer.children.length-1; index > 0; index--) {
            let layer:Node = this.allContainer.children[index];
            let layerItem:LayerItem = layer.getComponent(LayerItem);
            if (layerItem.info.layerId == addItem.belongLayer.layerId) {
                return;
            }

            let checkLayer:LayerInfo = layerItem.info;
            for (let x:number = beginX; x <= endX; x++) {
                for (let y:number = beginY; y <= endY; y++) {
                    let checkCard:CardItem = checkLayer.allCards.get(`${x}_${y}`);
                    if (checkCard != null) { //有，就覆盖了，影响到了。
                        console.log("这个卡牌被覆盖",addItem.belongLayer.layerId, addItem.pos.gridX, addItem.pos.gridY);
                        addItem.beCover = true;
                        return;
                    }
                }
            }
        }
    }




    /**
     * 自动添加关卡。无尽版
     */
    private autoAddLayer(){
        if (this.allContainer.children.length <= 3) {
            this.addLayer().addSomeCard(10);
        }
    }




}

export let gameManager: GameManager = new GameManager();


